var Config = {
	hosts : 'http://api.meite.com/',
    appid : 70,
    channel : 'default',
    deviceid : 1,
    appkey : 'b07f2c370e974f969a39708bc1277482',
    version : 'v1.0.0',
    Wx_appid :  'wx2332a26ec6ab05e6',
};

var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd';
function padding(s, len) {
    var len = len - (s + '').length;
    for (var i = 0; i < len; i++) { s = '0' + s; }
    return s;
};

function xssScript(s){ 
    var pattern = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")        //格式 RegExp("[在中间定义特殊过滤字符]")
    var rs = ""; 
    for (var i = 0; i < s.length; i++) { 
     rs = rs+s.substr(i, 1).replace(pattern, ''); 
    }
    return rs;
};


var Util = {
	formatDate: {
        // 格式化日期
        format: function (date, pattern) {
            pattern = pattern || DEFAULT_PATTERN;
            return pattern.replace(SIGN_REGEXP, function ($0) {
                switch ($0.charAt(0)) {
                    case 'y': return padding(date.getFullYear(), $0.length);
                    case 'M': return padding(date.getMonth() + 1, $0.length);
                    case 'd': return padding(date.getDate(), $0.length);
                    case 'w': return date.getDay() + 1;
                    case 'h': return padding(date.getHours(), $0.length);
                    case 'm': return padding(date.getMinutes(), $0.length);
                    case 's': return padding(date.getSeconds(), $0.length);
                }
            });
        },
        // 返回时间戳
        timestamp: function(){
            return Date.parse(new Date())/1000
        }
    },
    getUrlParams : function(name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return xssScript(unescape(r[2])); return null;
    },
    //去掉前后空格
    trim:function(str){
        return str.replace(/(^\s*)|(\s*$)/g, "")
    },
    // 转JSON 对象
    JsonParse:function(str){
        if ( !str ) { throw "JsonParse方法中传入的参数不存在或为空"; return;}
        return typeof str == 'object' ? str : JSON.parse(str)
    },
    /*//cookie 设置 获取 删除
    getItem:function(name){
        // return JSON.parse(sessionStorage.getItem(name || 'UserDate'));
        var cookieName = encodeURIComponent(name || 'UserDate') + '=',
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = null;

        if ( cookieStart > -1 ) {
            var cookieEnd = document.cookie.indexOf(';',cookieStart);
            if ( cookieEnd == -1 ) {
                cookieEnd = document.cookie.length;
            };
            cookieValue = decodeURIComponent( document.cookie.substring(cookieStart + cookieName.length,cookieEnd) );
        };
        return JSON.parse(cookieValue);
    },
    //设置本地存储数据
    //expires 小时
    setItem:function(name,obj,expires,path,domain,secure){
        console.log(11)
        if ( typeof obj != 'object' ) { throw "参数不是一个对象"; return;}
        // sessionStorage.setItem(name||'UserDate',JSON.stringify(obj));
        var value = JSON.stringify(obj);
        var cookieText = encodeURIComponent(name||'UserDate') + '=' + encodeURIComponent(value);

        var expires = expires || 1;
        if (typeof expires === 'number' ) {
            cookieText += '; max-age=' + (expires * 60 * 60);
        };
        if (path) {
            cookieText += '; path=' + path;
        };
        if ( domain ) {
            cookieText += '; domain=' + domain;
        };
        if ( secure ) {
            cookieText += '; secure';
        };
        document.cookie = ''+cookieText;
        console.log(document.cookie)
    },
    //移除本地数据
    removeItem:function(name,path,domain,secure){
        // sessionStorage.removeItem(name||'UserDate');
        this.setItem(name||'UserDate','',0,path,domain,secure);
    }*/
    getItem:function(name){
        return JSON.parse(sessionStorage.getItem(name || 'UserDate'));
    },
    //设置本地存储数据
    setItem:function(name,obj,expires,path,domain,secure){
        if ( typeof obj != 'object' ) { throw "参数不是一个对象"; return;}
        sessionStorage.setItem(name||'UserDate',JSON.stringify(obj));
    },
    //移除本地数据
    removeItem:function(name,path,domain,secure){
        sessionStorage.removeItem(name||'UserDate');
    }
}

var g = {
    isApp : (function(){ return Util.getUrlParams('isapp') == 1 ? true : false })(),
    isAndroid : (function(){ return /(Android)/i.test(navigator.userAgent); })(),
    isIOS : (function(){ return /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); })(),
    isWeiXin : (function(){ var ua = window.navigator.userAgent.toLowerCase(); var result = ua.match(/MicroMessenger/i) == 'micromessenger' ? true : false; return result })(),
    isWeibo : (function(){ return /(weibo)/i.test(navigator.userAgent.toLowerCase()) })(),
    isPhone6p : (function(){
        var h=window.innerHeight,w=window.innerWidth,useragent = navigator.userAgent.toLowerCase(),isP6p = false;
        if(useragent.match(/mobile/i)!==null && useragent.match(/iphone/i)!==null && ( h>w ? (Math.abs(w-414)<10 && h<=736) : (Math.abs(w-736)<10) && h<=414)) isP6p = true;
        return isP6p;
    })(),
    wxUrl:function(){
        var scope = (Util.getUrlParams('join') == 1) ? 'snsapi_base' : 'snsapi_userinfo';  // snsapi_base  snsapi_userinfo

        var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ Config.Wx_appid +'&redirect_uri='+encodeURIComponent(window.location.href)+'&response_type=code&scope='+ scope +'&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
        window.location.href= url;
    },
    getWxCode:function(){
        if ( this.isWeiXin ) {         //如果是微信
            var weixin_code = Util.getUrlParams('code');
            if ( !weixin_code ) {
                this.wxUrl();
            }else{
                return weixin_code;
            }
        }
    },
    wxLogin:function(callback){
        var self = this;
        if ( Util.getItem('UserDate') ) { return JSON.parse(Util.getItem('UserDate')); }
        var wxCode = self.getWxCode();
        if ( !wxCode ) { return; }

        $.ajax({
            url:requestUrl('Passport/Connect/login'),
            type:'post',
            data:{
                code: wxCode
            },
            success:function(data){
                var data = typeof data == 'object' ? data : JSON.parse(data);
                if ( data.Status == 200 ) {
                    Util.setItem('UserDate',data.Result);
                    if (typeof callback == 'function') {
                        callback(data.Result)
                    }
                }else if(data.Status == 205){       //code失效的情况  操作:复制链接到外部 点击链接进入
                    // 跳到不带code的地址
                    var w = window.location;
                    var hash = w.hash;
                    var origin = w.origin;
                    var pathname = w.pathname;
                    window.location.href = origin + pathname + hash;   
                }else{
                    console.log(data.Result.ErrorMsg)
                }
            }
        })


    }
};

function requestUrl(name,params,host){            //请求的url
    if (!name) { console.log('未传入调用方法'); return; }
    var host = host || Config.hosts;
    var str = '';
    for(var i in params){
    	str += params[i];
    }
    var hash = md5( Config.appkey + Config.version + name + Config.appid + Config.channel + Util.formatDate.timestamp() + Config.deviceid + str );
    var url = host + Config.version + '/' +name + '?appid='+Config.appid + '&channel='+ Config.channel + '&time='+Util.formatDate.timestamp() + '&deviceid='+Config.deviceid + '&hash='+hash;
    return url;
}

//重新刷新页面  此方法用于APP端 需刷新页面时使用
function reloadPage(){
    window.location.reload();
}



